#!/bin/sh
# PCP QA Test No. 1157
# Exercise the BCC PMDA tcpretrans module - install, remove and values.
#
# Copyright (c) 2018 Andreas Gerstmayr.
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.bcc

_pmdabcc_check
_bcc_check_ArgString || _notrun "bcc is broken (ArgString bug) on this platform"
case "`uname -srm`"
in
    Linux\ 5.2.*)
    		_notrun "Bad Linux 5.2 kernel headers will cause BPF to fail"
		;;
esac

if [ -f /etc/lsb-release ]
then
    . /etc/lsb-release
    if [ "$DISTRIB_ID" = Ubuntu ]
    then
	# This test fails for Ubuntu 19.10 because the linux headers used
	# by the BPF compiler appear to be knackered.
	#
	case "$DISTRIB_RELEASE"
	in
	    19.10)
		_notrun "bcc does not work for this test on Ubuntu $DISTRIB_RELEASE"
		;;
	esac
    fi
fi

# sch_netem is part of optional kernel-modules-extra on Fedora
$sudo modprobe sch_netem
lsmod | grep sch_netem >/dev/null 2>&1 \
  || _notrun "sch_netem kernel module not available"
which curl >/dev/null 2>&1 || _notrun "No curl binary installed"

target_ip=1.1.1.1
net_dev=$(ip route get ${target_ip} | awk '{print $5; exit}')

status=1       # failure is the default!
signal=$PCP_BINADM_DIR/pmsignal
$sudo rm -rf $tmp.* $seq.full

_simulate_network_troubles()
{
    echo Simulate packet loss
    $sudo tc qdisc add dev ${net_dev} root netem loss 100%
}

_revert_network_troubles()
{
    echo Revert intentional packet loss
    $sudo tc qdisc del dev ${net_dev} root 2>>$here/$seq.full
}

_value_filter()
{
    awk '/inst .*::'${target_ip}':80"] value/ {print "OK"; exit}'
}

_prepare_pmda bcc
trap "_revert_network_troubles; _pmdabcc_cleanup; exit \$status" 0 1 2 3 15
_stop_auto_restart pmcd

cat <<EOF | _pmdabcc_install
# Installed by PCP QA test $seq on `date`
[pmda]
modules = tcpretrans
prefix = bcc.
[tcpretrans]
module = tcpretrans
cluster = 9
EOF

_pmdabcc_wait_for_metric

# Generate system activity for the BCC tcpretrans module
_simulate_network_troubles
curl -s --connect-timeout 5 http://${target_ip}
_revert_network_troubles

echo "=== report metric values for count ==="
pminfo -dfmtT bcc.io.net.tcp.retrans.count 2>&1 | tee -a $here/$seq.full \
| _value_filter

_pmdabcc_remove

status=0
exit
